/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * OpenFilesFrame.java
 *
 * Created on 06/09/2010, 17:39:47
 */
package user_gui;

import core.Operadora;
import in_out.IOUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import utils.Tupla;
import java.util.Map;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
import op.Config;
import op.ContaTelefonica;

/**
 *
 * @author Jônatas
 */
public class OpenFilesFrame extends javax.swing.JFrame {

    private FramePrincipal parent;

    /** Creates new form OpenFilesFrame */
    public OpenFilesFrame(FramePrincipal parent) {
        this.parent = parent;
        this.parent.setEnabled(false);
        initComponents();
    }

    private void updateList() {
        ListModel model = new MapBasedListModel(arquivos);
        jList1.setModel(model);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroupOperadora = new javax.swing.ButtonGroup();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        radioButtonTIM = new javax.swing.JRadioButton();
        radioButtonVoip = new javax.swing.JRadioButton();
        radioButtonEmbratel = new javax.swing.JRadioButton();
        radioButtonOiContaTotal = new javax.swing.JRadioButton();
        radioButtonOi = new javax.swing.JRadioButton();
        radioButtonOiFixo = new javax.swing.JRadioButton();
        radioButtonVivo = new javax.swing.JRadioButton();
        radioButtonVivo2 = new javax.swing.JRadioButton();
        radioButtonPabxVicol = new javax.swing.JRadioButton();
        radioButtonPabxTaritron = new javax.swing.JRadioButton();
        radioButtonClaro = new javax.swing.JRadioButton();
        radioButtonGVT = new javax.swing.JRadioButton();
        radioButtonSiemens = new javax.swing.JRadioButton();
        radioButtonVivo3 = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Abrir arquivos");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jScrollPane1.setViewportView(jList1);

        jButton2.setText("Remover");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Adicionar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("OK");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        buttonGroupOperadora.add(radioButtonTIM);
        radioButtonTIM.setText("TIM");

        buttonGroupOperadora.add(radioButtonVoip);
        radioButtonVoip.setText("Voip");

        buttonGroupOperadora.add(radioButtonEmbratel);
        radioButtonEmbratel.setText("Embratel");

        buttonGroupOperadora.add(radioButtonOiContaTotal);
        radioButtonOiContaTotal.setText("Oi Conta Total");

        buttonGroupOperadora.add(radioButtonOi);
        radioButtonOi.setText("Oi");

        buttonGroupOperadora.add(radioButtonOiFixo);
        radioButtonOiFixo.setText("Oi Fixo");

        buttonGroupOperadora.add(radioButtonVivo);
        radioButtonVivo.setSelected(true);
        radioButtonVivo.setText("Vivo");

        buttonGroupOperadora.add(radioButtonVivo2);
        radioButtonVivo2.setText("Vivo 2");

        buttonGroupOperadora.add(radioButtonPabxVicol);
        radioButtonPabxVicol.setText("Rêmora");

        buttonGroupOperadora.add(radioButtonPabxTaritron);
        radioButtonPabxTaritron.setText("Taritron");

        buttonGroupOperadora.add(radioButtonClaro);
        radioButtonClaro.setText("Claro");

        buttonGroupOperadora.add(radioButtonGVT);
        radioButtonGVT.setText("GVT");

        buttonGroupOperadora.add(radioButtonSiemens);
        radioButtonSiemens.setText("Siemens");

        buttonGroupOperadora.add(radioButtonVivo3);
        radioButtonVivo3.setText("Vivo 3");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(radioButtonVivo)
                    .addComponent(radioButtonVivo2)
                    .addComponent(radioButtonVoip)
                    .addComponent(radioButtonEmbratel)
                    .addComponent(radioButtonTIM)
                    .addComponent(radioButtonOiContaTotal)
                    .addComponent(radioButtonOi)
                    .addComponent(radioButtonOiFixo))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(radioButtonPabxTaritron)
                    .addComponent(radioButtonPabxVicol)
                    .addComponent(radioButtonClaro)
                    .addComponent(radioButtonGVT)
                    .addComponent(radioButtonSiemens)
                    .addComponent(radioButtonVivo3))
                .addContainerGap(16, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioButtonVivo)
                    .addComponent(radioButtonPabxVicol))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(radioButtonPabxTaritron)
                    .addComponent(radioButtonOiFixo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioButtonOi)
                    .addComponent(radioButtonClaro))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioButtonOiContaTotal)
                    .addComponent(radioButtonGVT))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioButtonTIM)
                    .addComponent(radioButtonSiemens))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioButtonEmbratel)
                    .addComponent(radioButtonVivo3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radioButtonVoip)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radioButtonVivo2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {radioButtonEmbratel, radioButtonOi, radioButtonOiContaTotal, radioButtonOiFixo, radioButtonTIM, radioButtonVivo, radioButtonVivo2, radioButtonVoip});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton3)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-498)/2, (screenSize.height-351)/2, 498, 351);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        Object[] objects = jList1.getSelectedValues();

        for (Object o : objects) {
            arquivos.remove(o.toString());
        }

        updateList();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        addFiles();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void addFiles() {
        FramePrincipal.MyFilter filter = new FramePrincipal.MyFilter();

        Operadora operadora = null;

        if (radioButtonEmbratel.isSelected()) {
            operadora = Operadora.EMBRATEL;
        } else if (radioButtonOi.isSelected()) {
            operadora = Operadora.OI;
        } else if (radioButtonOiContaTotal.isSelected()) {
            operadora = Operadora.OI_CONTA_TOTAL;
        } else if (radioButtonOiFixo.isSelected()) {
            operadora = Operadora.OI_FIXO;
        } else if (radioButtonTIM.isSelected()) {
            operadora = Operadora.TIM;
        } else if (radioButtonVivo.isSelected()) {
            operadora = Operadora.VIVO;
        } else if (radioButtonVoip.isSelected()) {
            operadora = Operadora.VOIP;
            filter = new FramePrincipal.MyFilter(".xls");
        } else if (radioButtonVivo2.isSelected()) {
            operadora = Operadora.VIVO_2;
        } else if (radioButtonPabxVicol.isSelected()) {
            operadora = Operadora.PABX_VICOL;
        } else if (radioButtonPabxTaritron.isSelected()) {
            operadora = Operadora.PABX_TARITRON;
        } else if (radioButtonClaro.isSelected()) {
            operadora = Operadora.CLARO;
        } else if (radioButtonGVT.isSelected()) {
            operadora = Operadora.GVT;
        } else if (radioButtonSiemens.isSelected()) {
            operadora = Operadora.SIEMENS;
        } else if (radioButtonVivo3.isSelected()) {
            operadora = Operadora.VIVO_3;
        }


        String filePath = null;
        try {
            Config config = Config.getInstance();

            filePath = config.getPathChooserPrincipal();

        } catch (IOException ex) {
            ex.printStackTrace();
        }

        JFileChooser chooser = new JFileChooser(filePath);
        chooser.setFileFilter(filter);
        chooser.setMultiSelectionEnabled(true);
        chooser.showOpenDialog(this);

        File[] files = chooser.getSelectedFiles();

        for (File f : files) {
            Tupla<File, Operadora> tupla = new Tupla<File, Operadora>(f, operadora);

            arquivos.put(f.getName(), tupla);
        }

        try {
            Config config = Config.getInstance();

            filePath = files[0].getParent();

            config.setPathChooserPrincipal(filePath);

        } catch (IOException ex) {
            ex.printStackTrace();
        }

        updateList();
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

        Set<Tupla<File, Operadora>> arquivosAbertos = new HashSet<Tupla<File, Operadora>>();

        for (String key : arquivos.keySet()) {
            arquivosAbertos.add(arquivos.get(key));
        }

        ContaTelefonica conta = null;

        try {
            conta = IOUtils.openMultipleFiles(arquivosAbertos);
        } catch (Exception e) {
            if (e instanceof IOException) {
                JOptionPane.showMessageDialog(this, "Houve um problema na leitura do arquivo, por favor verifique se este"
                        + "arquivo não está sendo utilizado por outra aplicação.", "Erro", JOptionPane.ERROR_MESSAGE);
            } else if (e instanceof IllegalArgumentException) {
                JOptionPane.showMessageDialog(this, "Existe um problema na estrutura do arquivo, por favor verifique se este"
                        + "arquivo está correto.", "Erro", JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Ocorreu um erro inesperado favor entre em contato"
                        + "com o suporte.", "Erro", JOptionPane.ERROR_MESSAGE);
            }

            e.printStackTrace();

            return;
        }

        try {
            this.parent.setContaOriginal(conta);
        } catch (Exception e) {

            e.printStackTrace();

        } finally {
            closing();

            dispose();
        }

    }//GEN-LAST:event_jButton3ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        closing();
    }//GEN-LAST:event_formWindowClosing

    private void closing() {
        this.parent.setEnabled(true);
    }

    /*
     * Este mapa ira armazenar os arquivos a serem abertos.
     * A chave eh uma String que deve conter apenas o nome simples do arquivo.
     * O valor e uma Tupla, esta tupla ira conter o arquivo em si e a operadora utilizada.
     */
    private Map<String, Tupla<File, Operadora>> arquivos = new HashMap<String, Tupla<File, Operadora>>();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroupOperadora;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton radioButtonClaro;
    private javax.swing.JRadioButton radioButtonEmbratel;
    private javax.swing.JRadioButton radioButtonGVT;
    private javax.swing.JRadioButton radioButtonOi;
    private javax.swing.JRadioButton radioButtonOiContaTotal;
    private javax.swing.JRadioButton radioButtonOiFixo;
    private javax.swing.JRadioButton radioButtonPabxTaritron;
    private javax.swing.JRadioButton radioButtonPabxVicol;
    private javax.swing.JRadioButton radioButtonSiemens;
    private javax.swing.JRadioButton radioButtonTIM;
    private javax.swing.JRadioButton radioButtonVivo;
    private javax.swing.JRadioButton radioButtonVivo2;
    private javax.swing.JRadioButton radioButtonVivo3;
    private javax.swing.JRadioButton radioButtonVoip;
    // End of variables declaration//GEN-END:variables
}
